package com.likerSai;

/**
 * 寻找两个正序数组中位数
 *
 * @author sun.ye
 * @since 2021-04-22 10:33
 */
public class FindMedianSortedArrays {


    public static void main(String[] args) {
        int[] nums1 = {1,2};
        int[] nums2 = {3,4};
        System.out.println(findMedianSortedArrays(nums1,nums2));
    }


    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int i = 0,j = 0;
        int totalNums = nums1.length + nums2.length;
        int midIndex = totalNums / 2;
        boolean isOdd = (totalNums % 2) == 1 ;
        int[] allNums = new int[totalNums];
        int iAll = 0;

        while (iAll < totalNums){
            int num1 = getThisIndexFrom(nums1,i);
            int num2 = getThisIndexFrom(nums2,j);
            if(num1 < num2) {
                allNums[iAll] = num1;
                i++;
            }else {
                allNums[iAll] = num2;
                j++;
            }
            iAll++;
        }
        if (isOdd){
            return allNums[midIndex];
        }else {
            return (allNums[midIndex] + allNums[midIndex-1]) / 2d;
        }


    }

    public static int getThisIndexFrom(int[] nums , int index){
        if(nums.length == 0 || index >= nums.length){
            return Integer.MAX_VALUE;
        }else {
            return nums[index];
        }
    }

    public static int initMid(int[] nums1,int[] nums2){
        if (nums1.length == 0){
            return nums2[0];
        }else if (nums2.length == 0){
            return nums1[0];
        }else {
            return Math.min(nums1[0],nums2[0]);
        }
    }

    public static int initNext(int[] nums1,int[] nums2){
        if (nums1.length == 0){
            return nums2[0];
        }else if (nums2.length == 0){
            return nums1[0];
        }else {
            return Math.max(nums1[0],nums2[0]);
        }
    }


}